<template>
  <div class="invite-statistics">
    
    <!-- 搜索区域 -->
    <div class="search-area">
    
      
      <div class="search-form">
        <el-form :inline="true" :model="filterForm" size="small">
          <el-form-item label="渠道">
            <el-select v-model="filterForm.channel" placeholder="请选择渠道" style="width: 150px;" clearable>
              <el-option
                v-for="item in channelOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="用户UID">
            <el-input v-model="filterForm.uid" placeholder="请输入用户UID" clearable type="number"></el-input>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 表格内容 -->
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>邀请统计</span>
          <el-button 
            type="success" 
            size="small" 
            icon="el-icon-download"
            style="float: right;"
            @click="exportData"
            :loading="exportLoading">
            导出CSV
          </el-button>
        </div>
        
        <el-table
          :data="tableData"
          border
          stripe
          style="width: 100%"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
          class="invite-table"
          v-loading="loading"
        >
          <el-table-column prop="uid" label="被邀请人" width="120"></el-table-column>
          <el-table-column prop="parent1" label="邀请人" width="120"></el-table-column>
          <el-table-column prop="children1" label="下1级数量" width="120" align="center"></el-table-column>
          <el-table-column prop="children2" label="下2级数量" width="120" align="center"></el-table-column>
          <el-table-column prop="children3" label="下3级数量" width="120" align="center"></el-table-column>
          <el-table-column prop="children4" label="下4级数量" width="120" align="center"></el-table-column>
          <el-table-column prop="children5" label="下5级数量" width="120" align="center"></el-table-column>
          <el-table-column prop="children6" label="下6级数量" width="120" align="center"></el-table-column>
          <el-table-column prop="children7" label="下7级数量" width="120" align="center"></el-table-column>
          <el-table-column prop="children8" label="下8级数量" width="120" align="center"></el-table-column>
          <el-table-column prop="children9" label="下9级数量" width="120" align="center"></el-table-column>
          <el-table-column prop="channel" label="渠道" width="80" align="center"></el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { agentStatistic } from '@/api/user'
import { exportDataToCsv } from '@/utils/export'
import channelMixin from '@/mixins/channelMixin'

export default {
  name: 'InviteStatistics',
  mixins: [channelMixin],
  data() {
    return {
      filterForm: {
        channel: null,
        uid: ''
      },
      tableData: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      exportLoading: false
    }
  },
  methods: {
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },
    async fetchData() {
      this.loading = true
      try {
        const params = {
          channel: this.formatChannelParam(this.filterForm.channel),
          uid: this.filterForm.uid ? parseInt(this.filterForm.uid) : 0,
          page: this.currentPage,
          page_size: this.pageSize
        }
        
        console.log('===== InviteStatistics Debug Info =====')
        console.log('发送参数:', params)
        
        const response = await agentStatistic(params)
        console.log('接口返回完整数据:', response)
        
        if (response && response.code === 0) {
          console.log('接口成功，response.data:', response.data)
          console.log('response.data的类型:', typeof response.data)
          console.log('response.data的结构:', Object.keys(response.data || {}))
          
          // 尝试多种可能的数据结构
          let records = []
          if (response.data && response.data.agents && Array.isArray(response.data.agents)) {
            records = response.data.agents
            console.log('使用 response.data.agents')
          } else if (response.data && response.data.records && Array.isArray(response.data.records)) {
            records = response.data.records
            console.log('使用 response.data.records')
          } else if (response.data && response.data.list && Array.isArray(response.data.list)) {
            records = response.data.list
            console.log('使用 response.data.list')
          } else if (Array.isArray(response.data)) {
            records = response.data
            console.log('使用 response.data 直接数组')
          } else if (response.data && response.data.data && Array.isArray(response.data.data)) {
            records = response.data.data
            console.log('使用 response.data.data')
          } else {
            console.log('未找到数组数据，尝试遍历所有属性:')
            if (response.data && typeof response.data === 'object') {
              for (let key in response.data) {
                console.log(`response.data.${key}:`, response.data[key], 'isArray:', Array.isArray(response.data[key]))
                if (Array.isArray(response.data[key])) {
                  records = response.data[key]
                  console.log(`找到数组数据在 response.data.${key}`)
                  break
                }
              }
            }
          }
          
          console.log('解析后的records:', records)
          console.log('records长度:', records.length)
          console.log('records第一条数据:', records[0])
          
          // 直接使用API返回的数据
          this.tableData = records
          
          // 处理总数
          if (response.data && response.data.total_page) {
            this.total = response.data.total_page * this.pageSize
          } else if (response.data && response.data.total) {
            this.total = response.data.total
          } else if (response.total_page) {
            this.total = response.total_page * this.pageSize
          } else if (response.total) {
            this.total = response.total
          } else {
            this.total = records.length
          }
          
          console.log('设置tableData长度:', this.tableData.length)
          console.log('当前tableData:', this.tableData)
          console.log('设置total:', this.total)
          
          // 强制视图更新
          this.$nextTick(() => {
            this.$forceUpdate()
          })
          
        } else {
          console.error('接口返回错误:', response)
          this.$message.error(response.msg || response.message || '获取数据失败')
        }
      } catch (error) {
        console.error('获取邀请统计数据失败:', error)
        this.$message.error('获取数据失败: ' + error.message)
      } finally {
        this.loading = false
      }
    },
    handleSearch() {
      this.currentPage = 1
      this.fetchData()
    },
    resetFilter() {
      this.filterForm.channel = null
      this.filterForm.uid = ''
      this.currentPage = 1
      this.fetchData()
    },
    async exportData() {
      this.exportLoading = true
      try {
        const params = {
          uid: this.filterForm.uid ? parseInt(this.filterForm.uid) : 0,
          channel: this.formatChannelParam(this.filterForm.channel),
          page: 1,
          page_size: 10000
        }
        
        const response = await agentStatistic(params)
        const allData = response.data.agents || []
        
        const columns = [
          { prop: 'uid', label: '被邀请人' },
          { prop: 'parent1', label: '邀请人' },
          { prop: 'children1', label: '下1级数量' },
          { prop: 'children2', label: '下2级数量' },
          { prop: 'children3', label: '下3级数量' },
          { prop: 'children4', label: '下4级数量' },
          { prop: 'children5', label: '下5级数量' },
          { prop: 'children6', label: '下6级数量' },
          { prop: 'children7', label: '下7级数量' },
          { prop: 'children8', label: '下8级数量' },
          { prop: 'children9', label: '下9级数量' },
          { prop: 'channel', label: '渠道' }
        ]
        
        const now = new Date()
        const dateStr = now.getFullYear() + 
          String(now.getMonth() + 1).padStart(2, '0') + 
          String(now.getDate()).padStart(2, '0') + '_' +
          String(now.getHours()).padStart(2, '0') + 
          String(now.getMinutes()).padStart(2, '0')
        
        const fileName = `邀请统计_${dateStr}.csv`
        exportDataToCsv(allData, columns, fileName)
        this.$message.success('导出成功！')
      } catch (error) {
        this.$message.error('导出失败')
        console.error(error)
      } finally {
        this.exportLoading = false
      }
    }
  },
  mounted() {
    this.fetchData()
  }
}
</script>

<style scoped>
.invite-statistics {
  padding: 20px;
}

h2 {
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: bold;
}

.search-area {
  margin-bottom: 20px;
}

.search-options {
  margin-bottom: 10px;
}

.search-label {
  font-size: 14px;
  margin-right: 20px;
  color: #f56c6c;
}

.invite-table {
  border: 1px solid #e6e6e6;
}

.level-cell {
  display: flex;
  align-items: center;
  width: 100%;
}

.count-cell {
  flex: 1;
  text-align: center;
  padding: 0 10px;
  border-right: 1px solid #EBEEF5;
}

.detail-cell {
  flex: 1;
  text-align: center;
}

.detail-cell .el-button {
  padding: 0 10px;
  margin: 0;
  color: #409EFF;
}

.table-footer {
  margin-top: 10px;
  margin-bottom: 10px;
  color: #f56c6c;
  font-size: 14px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 